import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:oramemo/common/langs/text_key.dart';
import 'package:oramemo/pages/facility/devices/ercode_not_device.dart';
import 'package:oramemo/pages/facility/facility_router.dart';

import 'device_info_page.dart';

class ScanningPage extends StatefulWidget {
  final Function(String)? onScan; // Callback to handle scanned code

  const ScanningPage({super.key, this.onScan});

  @override
  State<ScanningPage> createState() => _ScanningPageState();
}

class _ScanningPageState extends State<ScanningPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  final AudioPlayer _audioPlayer = AudioPlayer();
  bool backing = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        MobileScanner(
          onDetect: (barcode) {
            if (!backing) {
              backing = true;
              final String? code = barcode.barcodes[0].rawValue;
              if (code?.isNotEmpty == true) {
                _audioPlayer.play(AssetSource('sounds/success.mp3'));
                // widget.onScan(code!); // Call the callback with the scanned code
                // Get.toNamed(FacilityRouter.deviceBindPage, arguments: code);
                Get.back(result: code);
              }
            }
          },
        ),
        Container(
          color: Colors.black54,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  width: Get.width * 0.8,
                  height: Get.width * 1.0,
                  // decoration: BoxDecoration(
                  //   border: Border.all(color: Colors.green, width: 1),
                  //   borderRadius: BorderRadius.circular(12),
                  // ),
                  child: AnimatedBuilder(
                    animation: _animationController,
                    builder: (context, child) {
                      return CustomPaint(
                        painter: ScanningAnimationPainter(
                            _animationController.value),
                      );
                    },
                  ),
                ),
                const SizedBox(height: 60),
              ],
            ),
          ),
        ),
        SafeArea(
          child: IconButton(
            padding: const EdgeInsets.all(12),
            icon: const Icon(
              Icons.close,
              color: Colors.white,
            ),
            onPressed: () {
              Get.back(); // Close the scanning page
            },
          ),
        ),
        Positioned(
          bottom: 60,
          child: SafeArea(
            child: Container(
              width: Get.width,
              alignment: Alignment.center,
              child: Text(
                TextKey.scanningPageTitle.tr,
                style: const TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class ScanningAnimationPainter extends CustomPainter {
  final double progress;

  ScanningAnimationPainter(this.progress);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..strokeWidth = 5
      ..color = Colors.green.withOpacity(0.4)
      ..style = PaintingStyle.fill;

    // Draw a moving line to simulate scanning
    double lineY = size.height * progress;
    canvas.drawLine(Offset(0, lineY), Offset(size.width, lineY), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
